
import { Message } from "@/types/chat"
// 初始状态值参数
export type State = {
    dispalyNavigation: boolean
    messageList: Message[]
}

// 定义枚举类型
export enum ActionType {
    UPDATE= 'UPDATE',
    ADD_MESSAGE = 'ADD_MESSAGE',
    UPDATE_MESSAGE = 'UPDATE_MESSAGE'
}
type MessageAction = {
    type: ActionType.ADD_MESSAGE | ActionType.UPDATE_MESSAGE
    message: Message
}

// 更新数据传递的参数
type UpdateAction = {
    type: ActionType.UPDATE
    fieId: string
    value: any
}

export type Action = UpdateAction | MessageAction

// 初始化状态
export const initialState: State = {
    dispalyNavigation: true,
    messageList: [
        {
            id: '1',
            role: 'user',
            content: 'hello`npm run dev`',
            createTime: Date.now()
        },
        {
            id: '2',
            role: 'assistant',
            content: 'hi`npm run dev,http://localhost:3000/chat`',
            createTime: Date.now()
        }
    ],
}

export function reducer(
    state: State = initialState,
    action: Action //动作状态
): State {
    switch (action.type) {
        case ActionType.UPDATE:
            return {
                ...state,
                [action.fieId]: action.value
            }
        case ActionType.ADD_MESSAGE:
            const messageList = [...state.messageList, action.message]
            return{ ...state, messageList }
        case ActionType.UPDATE_MESSAGE:
            const newMessageList = state.messageList.map((message) => {
                if (message.id === action.message.id) {
                    return action.message
                }
                return message
            })

        default: throw new Error()
    }
}